import React, { useState } from 'react';
import styled from 'styled-components';
import { useLocation, useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useSelector } from 'react-redux';
import { PageLayout } from '@/components/grid/PageLayout';
import {
  List,
  Card,
  Radio,
  Button,
  Toast,
  Dialog,
  Tag,
} from 'antd-mobile';
import {
  PayCircleOutline,
  CouponOutline,
  CheckCircleFill,
} from 'antd-mobile-icons';

interface CartItem {
  id: string;
  name: string;
  price: number;
  quantity: number;
}

interface Coupon {
  id: string;
  name: string;
  discount: number;
  minAmount: number;
  expireDate: string;
}

const mockCoupons: Coupon[] = [
  {
    id: '1',
    name: '满30减5元',
    discount: 5,
    minAmount: 30,
    expireDate: '2024-12-31',
  },
  {
    id: '2',
    name: '满50减10元',
    discount: 10,
    minAmount: 50,
    expireDate: '2024-12-31',
  },
];

const Payment: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const location = useLocation();
  const theme = useSelector((state: any) => state.theme);
  const { items, totalAmount } = location.state || { items: [], totalAmount: 0 };
  const [selectedCoupon, setSelectedCoupon] = useState<Coupon | null>(null);
  const [paymentMethod, setPaymentMethod] = useState<'wechat' | 'alipay'>('wechat');
  const [orderId] = useState(() => 
    'ORDER' + Date.now().toString().slice(-8) + Math.random().toString(36).slice(-4).toUpperCase()
  );

  const handleCouponSelect = (coupon: Coupon) => {
    if (totalAmount < coupon.minAmount) {
      Toast.show({
        content: t('订单.支付.优惠券.不满足条件'),
      });
      return;
    }
    setSelectedCoupon(coupon);
  };

  const getFinalAmount = () => {
    if (!selectedCoupon) return totalAmount;
    return Math.max(0, totalAmount - selectedCoupon.discount);
  };

  const handlePayment = async () => {
    Toast.show({
      icon: 'loading',
      content: t('订单.支付.处理中'),
      duration: 1000,
    });

    // 模拟支付过程
    setTimeout(() => {
      Dialog.alert({
        content: t('订单.支付.成功'),
        confirmText: t('通用.确认'),
        onConfirm: () => {
          navigate('/orders');
        },
      });
    }, 1500);
  };

  return (
    <PageLayout title={t('订单.支付.标题')}>
      <Container>
        <Card>
          <OrderInfo>
            <OrderTitle>{t('订单.支付.订单信息')}</OrderTitle>
            <OrderId>{t('订单.支付.订单号')}: {orderId}</OrderId>
          </OrderInfo>

          <List>
            {items.map((item: CartItem) => (
              <List.Item
                key={item.id}
                extra={`x${item.quantity}`}
              >
                <ItemRow>
                  <span>{item.name}</span>
                  <Price $theme={theme}>¥{(item.price * item.quantity).toFixed(2)}</Price>
                </ItemRow>
              </List.Item>
            ))}
          </List>
        </Card>

        <Card>
          <Section>
            <SectionTitle>
              <CouponOutline /> {t('订单.支付.优惠券')}
            </SectionTitle>
            <CouponList>
              {mockCoupons.map(coupon => (
                <CouponItem
                  key={coupon.id}
                  $active={selectedCoupon?.id === coupon.id}
                  $theme={theme}
                  onClick={() => handleCouponSelect(coupon)}
                >
                  <CouponInfo>
                    <CouponName>{coupon.name}</CouponName>
                    <CouponCondition>
                      {t('订单.支付.优惠券.满减条件', { amount: coupon.minAmount })}
                    </CouponCondition>
                  </CouponInfo>
                  {selectedCoupon?.id === coupon.id && (
                    <CheckCircleFill style={{ fontSize: 20 }} />
                  )}
                </CouponItem>
              ))}
            </CouponList>
          </Section>
        </Card>

        <Card>
          <Section>
            <SectionTitle>
              <PayCircleOutline /> {t('订单.支付.支付方式')}
            </SectionTitle>
            <Radio.Group
              value={paymentMethod}
              onChange={val => setPaymentMethod(val as 'wechat' | 'alipay')}
            >
              <PaymentOption>
                <Radio value="wechat">{t('订单.支付.微信支付')}</Radio>
              </PaymentOption>
              <PaymentOption>
                <Radio value="alipay">{t('订单.支付.支付宝')}</Radio>
              </PaymentOption>
            </Radio.Group>
          </Section>
        </Card>

        <Footer $theme={theme}>
          <PriceInfo>
            <span>{t('订单.支付.应付金额')}:</span>
            <FinalPrice $theme={theme}>
              ¥{getFinalAmount().toFixed(2)}
              {selectedCoupon && (
                <OriginalPrice>¥{totalAmount.toFixed(2)}</OriginalPrice>
              )}
            </FinalPrice>
          </PriceInfo>
          <PayButton
            color="primary"
            onClick={handlePayment}
            block
          >
            {t('订单.支付.确认支付')}
          </PayButton>
        </Footer>
      </Container>
    </PageLayout>
  );
};

export default Payment;

const Container = styled.div`
  padding: 12px;
  padding-bottom: 80px;

  .adm-card {
    border-radius: 12px;
    margin-bottom: 12px;
  }
`;

const OrderInfo = styled.div`
  margin-bottom: 16px;
`;

const OrderTitle = styled.h2`
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 8px;
`;

const OrderId = styled.div`
  font-size: 14px;
  color: var(--adm-color-text-secondary);
`;

const ItemRow = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
`;

const Price = styled.span<{ $theme: string }>`
  font-weight: 500;
  color: var(--adm-color-primary);

  ${props => props.$theme === 'pink' && `
    color: #EC4899;
  `}

  ${props => props.$theme === 'green' && `
    color: #10B981;
  `}

  ${props => props.$theme === 'sky' && `
    color: #0EA5E9;
  `}
`;

const Section = styled.div`
  padding: 8px 0;
`;

const SectionTitle = styled.div`
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
`;

const CouponList = styled.div`
  display: flex;
  flex-direction: column;
  gap: 12px;
`;

const CouponItem = styled.div<{ $active: boolean; $theme: string }>`
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid var(--adm-color-border);
  cursor: pointer;
  transition: all 0.3s ease;

  ${props => props.$active && `
    border-color: var(--adm-color-primary);
    background: var(--adm-color-box);
  `}

  ${props => props.$theme === 'pink' && props.$active && `
    border-color: #EC4899;
    color: #EC4899;
  `}

  ${props => props.$theme === 'green' && props.$active && `
    border-color: #10B981;
    color: #10B981;
  `}

  ${props => props.$theme === 'sky' && props.$active && `
    border-color: #0EA5E9;
    color: #0EA5E9;
  `}
`;

const CouponInfo = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;
`;

const CouponName = styled.div`
  font-size: 16px;
  font-weight: 500;
`;

const CouponCondition = styled.div`
  font-size: 14px;
  color: var(--adm-color-text-secondary);
`;

const PaymentOption = styled.div`
  padding: 12px 0;
`;

const Footer = styled.div<{ $theme: string }>`
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);

  ${props => props.$theme === 'pink' && `
    box-shadow: 0 -2px 10px rgba(236, 72, 153, 0.05);
  `}

  ${props => props.$theme === 'green' && `
    box-shadow: 0 -2px 10px rgba(16, 185, 129, 0.05);
  `}

  ${props => props.$theme === 'sky' && `
    box-shadow: 0 -2px 10px rgba(14, 165, 233, 0.05);
  `}
`;

const PriceInfo = styled.div`
  display: flex;
  align-items: baseline;
  gap: 8px;
`;

const FinalPrice = styled.div<{ $theme: string }>`
  font-size: 20px;
  font-weight: 600;
  color: var(--adm-color-danger);
  display: flex;
  align-items: baseline;
  gap: 8px;
`;

const OriginalPrice = styled.span`
  font-size: 14px;
  color: var(--adm-color-text-secondary);
  text-decoration: line-through;
`;

const PayButton = styled(Button)`
  min-width: 120px;
  --border-radius: 20px;
`; 